package tasks

import (
	"reflect"
	"runtime"
	"time"
	"wiliwili/util"

	"github.com/robfig/cron"
)

// Cron 定时器单例
var Cron *cron.Cron

// Run 运行
func Run(job func() error) {
	from := time.Now().UnixNano()
	err := job()
	to := time.Now().UnixNano()
	jobName := runtime.FuncForPC(reflect.ValueOf(job).Pointer()).Name()
	if err != nil {
		util.Log().Info("%s error: %d ms", jobName, (to-from)/int64(time.Millisecond))
	} else {
		util.Log().Info("%s success: %d ms", jobName, (to-from)/int64(time.Millisecond))
	}
}

// CronJob 定时任务
func CronJob() {
	if Cron == nil {
		Cron = cron.New()
	}
	Cron.AddFunc("0 0 0 * * *", func() { Run(RestartDailyRank) })
	// 10秒一次
	Cron.AddFunc("*/10 * * * * *", func() { Run(LotusClient) })
	Cron.Start()

	util.LogD("CronJob", "start.....")
}
